using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace InsertVideoForHostedWordpress
{
    [WriterPlugin("da9698b8-d0bf-4e13-be00-a7d0bd678579", "Insert Video For Hosted Wordpress",
        Description = "As Hosted Wordpress doesn't allow normal video embedding, this one puts in the code it expects.",
        HasEditableOptions = false,
        Name = "Insert Video For Hosted Wordpress",
        PublisherUrl = "http://scottisafooldev.spaces.live.com",
        ImagePath= "icon.gif")]
    [InsertableContentSource("Video For Wordpress")]

    public class InsertVideoJnr : ContentSource
    {
        // If you change the name after class, please change it here too
        public InsertVideoJnr()
        { }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string newContent)
        {
            using (frmMain main = new frmMain())
            {
                DialogResult result = main.ShowDialog();
                if (result == DialogResult.OK)
                {
                    newContent = string.Format("[{0}={1}]", main.VideoType, main.VideoLink);

                    if(main.IncludeTitle){
                        string title = GetHtmlPageSource(main.VideoLink);
                        newContent += "\n<br />\n" +
                            "<a href=\"" + main.VideoLink + "\">" + title + "</a>";                         

                    }
                }
                return result;
            }            
        }

        public string GetHtmlPageSource (string link)
        {
                System.IO.Stream st = null;
                System.IO.StreamReader sr = null;
                string t = "";

                try
                {
                    // make a Web request
                    System.Net.WebRequest req = System.Net.WebRequest.Create(link);

                    // get the response and read from the result stream
                    System.Net.WebResponse resp = req.GetResponse();
                    st = resp.GetResponseStream();
                    sr = new System.IO.StreamReader(st);

                    // read all the text in it
                    t = sr.ReadToEnd();
                    t = GetTitle(t);
                }
                catch
                {
                    return string.Empty;
                }
                finally
                {
                    // always close readers and streams
                    sr.Close();
                    st.Close();
                }
                return t;
        }    
        
        public string GetTitle(string Source)
        {
            Match m = Regex.Match(Source, "<title>(.*?)</title>");
            if (m.Success)
                return m.Groups[1].Value;
            else
                return null;

            /*string tag = "<title";
            string title = "      ";
            int len = Source.Length;

            char c;
            for (int i = 0; i < len; i++)
            {
                c = Convert.ToChar(Source.Substring(i, 1));
                title = title.Remove(0, 1);
                title += c;
                if (title.ToLower() == tag)
                {
                    while (c != '>')
                    {
                        i++;
                        c = Convert.ToChar(Source.Substring(i, 1));
                    }
                    title = "";
                    i++;
                    c = Convert.ToChar(Source.Substring(i, 1));
                    while (c != '<')
                    {
                        title += c;
                        i++;
                        c = Convert.ToChar(Source.Substring(i, 1));
                    }
                    break;
                }
            }
            return title.Trim();*/
        }

        /*public override SmartContentEditor CreateEditor(ISmartContentEditorSite editorSite)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            throw new Exception("The method or operation is not implemented.");
        }*/
    }
}
